import 'dart:developer';

import 'package:FlutterDemo/widget/practicalextension/flutterbloc/practicale/models/CommonEntry.dart';
import 'package:flutter/material.dart';

import 'practicale/blocs/MoviesBloc.dart';

/// 项目位于：practicale目录
/// 涉及到的包:  第三方库 rxdart: http:
/// 资料: https://www.jianshu.com/p/1ca0d64fe329
class SampleFlutterBloc3 extends StatelessWidget {
  final moviesBloc = MoviesStreamBloc();

  SampleFlutterBloc3({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // 加载数据
    moviesBloc.featchAllMovies();
    return Scaffold(
      appBar: AppBar(
        title: Text("Popular Movies"),
      ),
      body: StreamBuilder(
        stream: moviesBloc.allMovies,
        builder: (context, AsyncSnapshot<PhoneEntry> snapshot) {
          if (snapshot.hasData) {
            return buildList(snapshot);
          } else if (snapshot.hasError) {
            return Text(snapshot.error.toString());
          }
          return Center(
            child: CircularProgressIndicator(),
          );
        },
      ),
    );
  }

  Widget buildList(AsyncSnapshot<PhoneEntry> snapshot) {
    return buildGridView(snapshot);
  }

  ListView buildListView(AsyncSnapshot<PhoneEntry> snapshot) {
    return ListView.separated(
        itemBuilder: (context, index) {
          var len = snapshot.data!.list.length;
          log("index: $index , list-len: ${len} , newIndex: ${index % len}");
          return Container(
            height: 100,
            color: Colors.primaries[index % Colors.primaries.length],
            child: Center(
              child: Text(
                "${snapshot.data!.list[index].value}",
                style: Theme.of(context).textTheme.headline3,
                textAlign: TextAlign.center,
              ),
            ),
          );
        },
        separatorBuilder: (context, index) {
          return Divider();
        },
        itemCount: snapshot.data!.list.length);
  }

  Widget buildGridView(AsyncSnapshot<PhoneEntry> snapshot) {
    return GridView.builder(
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
      itemCount: snapshot.data!.list.length,
      itemBuilder: (BuildContext context, int index) {
        return Container(
          color: Colors.primaries[index % Colors.primaries.length],
          child: Center(
            child: Text(
              "${snapshot.data!.list[index].value}",
              style: TextStyle(fontSize: 32, color: Colors.white),
            ),
          ),
        );
      },
    );
  }
}
